package com.ruoyi.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

@Slf4j
public class VideoUtil {

    public static void main(String[] args) throws Exception {
//        OutputStream outputStream = new FileOutputStream("E:\\周报\\test.jpeg");
//        OutputStream outputStream2 = new FileOutputStream("E:\\周报\\test2.jpeg");
//        long duration = getVideoMap("E:\\周报\\video1.mp4", outputStream);
//        long duration2 = getVideoMap("http://58.213.110.131:8450/ycsddbh/incidentReport/2022/12/19/ee851e9229564631b78c2a3f0bbd222d.mp4", outputStream2);
//        System.out.println(duration);
//        System.out.println(duration2);
//
//        System.out.println(getAudioLength("E:\\wechat-file\\WeChat Files\\wxid_tw2civguh79722\\FileStorage\\File\\2022-12\\2_12-18_09_26_下载音频1.mp3"));
    }

    /**
     * 获取音频时长
     */
    public static long getAudioLength(String filePath) {
        long duration = 0;
        try {
            FFmpegFrameGrabber grabberOne = FFmpegFrameGrabber.createDefault(filePath);
            grabberOne.start();
            // 计算时长
            duration = grabberOne.getFormatContext().duration() / 1000000;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return duration;
    }

    /**
     * 获取 视频时长 + 首帧
     * @return
     */
    public static long getVideoMap(String filePath, OutputStream outputStream) {
        long duration = 0;
        try {

            FFmpegFrameGrabber fFmpegFrameGrabber = FFmpegFrameGrabber.createDefault(filePath);
            fFmpegFrameGrabber.start();
            // 获取视频的总帧数
            int lengthInFrames = fFmpegFrameGrabber.getLengthInFrames();
            double frameNumber = fFmpegFrameGrabber.getFrameRate();
            // 视频的时长
            double intLength = lengthInFrames / frameNumber;
            if(intLength > 0){
                duration = (long) intLength;
            }

            Frame frame = null;
            /** 从第3帧开始取 */
            for (int i = 3; i < lengthInFrames; i++) {
                frame = fFmpegFrameGrabber.grabFrame();
                if (frame.image != null) {
                    break;
                }
            }
            if (frame != null) {
                BufferedImage bufferedImage = new Java2DFrameConverter().getBufferedImage(frame);
                ImageIO.write(bufferedImage, "jpeg", outputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
        return duration;
    }

}